/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jse.concurrent;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author WangShuai
 */
public class TestSyn implements Runnable {
    /*
     * 当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时，
     * 一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。 
     */

    public void run() {
        synchronized (this) {
            for (int i = 0; i < 50; i++) {
                System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
                if (i == 10) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(TestSyn.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        TestSyn t1 = new TestSyn();
        Thread ta = new Thread(t1, "A");
        Thread tb = new Thread(t1, "B");
        ta.start();
        tb.start();
    }
}
